/*
 * Project Name spring-boot-tools
 * File Name KeepAliveMessageFactoryImpl
 * Package Name com.huxiaosu.tools.mina.filter
 * Create Time 2024/5/25
 * Create by name：liujie
 */
package com.huxiaosu.tools.mina.filter;

import com.alibaba.fastjson2.JSONObject;
import com.huxiaosu.tools.mina.model.BaseMessage;
import com.huxiaosu.tools.mina.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;

import java.io.UnsupportedEncodingException;

/**
 * Description
 *
 * @author liujie
 * @date 2024/5/25 13:39
 */
@Slf4j
public class KeepAliveMessageFactoryImpl implements KeepAliveMessageFactory {
    @Override
    public boolean isRequest(IoSession session, Object message) {
        BaseMessage command = null;
        try {
            command = (BaseMessage) message;
        } catch (Exception e) {
            return false;
        }
        if(command.getType() == Constants.T101){
            log.info("< keep live ...> ");
            return true;
        }
        return false;
    }

    @Override
    public boolean isResponse(IoSession session, Object message) {
        return false;
    }

    @Override
    public Object getRequest(IoSession session) {
        return null;
    }

    @Override
    public Object getResponse(IoSession session, Object request) {
        BaseMessage requestMessage = (BaseMessage) request;

        log.info("服务端接收心跳请求数据：{}" , requestMessage.toString());

        JSONObject json = new JSONObject();
        json.put("status", Constants.SUCCESS);
        json.put("result", "keep live success");
        try {
            requestMessage.setBody(json.toString().getBytes(Constants.CHARSET));
            requestMessage.setBodyLength(json.toString().getBytes(Constants.CHARSET).length);
        } catch (UnsupportedEncodingException e) {
            log.debug("响应心跳请求异常" + e);
        }
        return requestMessage.toByte();
    }
}
